var event = require('../../../../utils/event.js')
var regeneratorRuntime = require('../../../../lib/js/runtime-module.js')
import config from '../../../../utils/config2'
import util from '../../../../utils/util2'
import Serv from '../walletServ'
let TimerClass = util.TimerClass

let timerObj = null//计时器实例
Page({

  /**
   * 页面的初始数据
   */
  data: {
    disabled: false,
    isSendMsg: false,
    userInfo: {},
    countText: '发送验证码',
    token: '',//从获取验证码接口取到的token
    timeCount: 0,
    verify_code: '',
    password: {},
    inputDisable: false,
    reg_phone_new: '',
    reg_phone: ''
  },
  // 发送验证码
  sendMsg: async function () {
    let { user_id, reg_phone_new, reg_phone, password } = this.data
    let errormsg = ''
    let regMag = {
      mobile: /^1[345678]\d{9}$/,//手机
    }
    if (!regMag.mobile.test(reg_phone)) {
      errormsg = '旧手机号码有误，请填写正确'
    }
    else if (!regMag.mobile.test(reg_phone_new)) {
      errormsg = '新手机号码有误，请填写正确'
    }
    else if (password && !password.pwdMw_new) {
      errormsg = '交易密码不能为空'
    }
    if (errormsg) {
      wx.showToast({
        title: errormsg || '',
        icon: 'none',
      })
      return false
    }
    if (timerObj == null) {//计时器实例化
      timerObj = new TimerClass(60, (timeCount, countText) => {
        let disabled = countText !== '获取验证码'
        this.setData({
          timeCount: timeCount,
          disabled: disabled,
          countText: countText,
          isSendMsg: true,
        })
      })
    }
    // 计时器状态
    if (timerObj.disabled) {
      return false
    }
    timerObj.start()
    console.log('sendMsg', password)
    //发起请求
    let params = {
      user_id: user_id,
      reg_phone_new,
      reg_phone,
      password: password.pwdMw,
      random_key: password.randomKey
    }
    // 发送请求
    let { success, msg, data } = await Serv.mobileChangeApply(params)
    if (!success) {
      timerObj.stop()
      this.setData({ isSendMsg: false, })
      wx.showToast({
        title: msg || '',
        icon: 'none',
        duration:3000
      })
      return false
    }

    this.setData({ token: data.token || '', txn_seqno: data.txn_seqno })
  },
  // 表单输入
  bindinput: function (e) {
    console.log('bindinput', e.currentTarget.dataset, e.detail)
    let label = e.currentTarget.dataset.label
    let value = e.detail.value
    this.setData({
      [label]: value,
    })
  },

  // 修改手机号码
  mobileChangeVerify: async function () {
    let { user_id, verify_code, txn_seqno, reg_phone, reg_phone_new, password,token } = this.data
    //发起请求
    let params = {
      user_id,
      txn_seqno,
      token,
      verify_code_new: verify_code
    }

    // 校验
    let errormsg = ''
    if (verify_code === '') {
      errormsg = '请输入验证码'
    }
    else if (!reg_phone) {
      errormsg = '旧手机号码不能为空'
    }
    else if (!reg_phone_new) {
      errormsg = '新手机号码不能为空'
    }
    else if (password && !password.pwdMw_new) {
      errormsg = '交易密码不能为空'
    }
    if (errormsg) {
      wx.showToast({
        title: errormsg || '',
        icon: 'none',
        duration:3000
      })
      return false
    }

    let { success, msg, data } = await Serv.mobileChangeVerify(params)
    if (!success) {
      wx.showToast({
        title: msg || '',
        icon: 'none',
      })
      return false
    }
    wx.showModal({
      title: '提示',
      content: '操作成功',
      showCancel: false,
      complete: (res) => {
        wx.redirectTo({
          url: '../index/index',
        })
      }
    })
  },
  //唤起密码控件
  pwdFocus: function (e) {
    let label = e.currentTarget.dataset.label
    // from：当前地址， eventName: 监听定义的事件名
    util.navigateStateChange(this, 'inputDisable')
    wx.navigateTo({
      url: '../../pwdCtrl/pwdCtrl?from=/wallet/password/password&eventName=onPwdChange' + `&label=${label}`
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let walletInfo = wx.getStorageSync('walletInfo');
    let user_id =walletInfo&&walletInfo.llWalletId?walletInfo.llWalletId:wx.getStorageSync(config.userIdKey) 
    let phoneNo = walletInfo&&walletInfo.mobile?walletInfo.mobile:''
    // console.log('onLoad user_id',user_id)
    this.setData({ user_id, phoneNo })
    //监听密码控件输入
    var that = this
    event.on('onPwdChange', that, function (changedData = {}) {
      let { pwdMw = '', label = '', randomKey = '', pwdHash = '', pwdlen = 0 } = changedData
      console.log('DataChanged trigger...', changedData, {
        [label]: pwdMw
      })
      that.setData({
        [label]: {
          pwdMw: pwdMw,
          randomKey: randomKey,
          pwdHash: pwdHash,
          pwdlen: pwdlen,
          pwdMw_new: pwdMw.substr(0, pwdlen),
        },
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var pages = getCurrentPages() //获取加载的页面
    var currentPage = pages[pages.length - 1] //获取当前页面的对象
    console.log('pages:', pages, 'currentPage:', currentPage)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var that = this
    //取消监听
    event.remove('onPwdChange', that)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {
  //
  // }
})
